package com.axin.web.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.axin.blog.api.domain.WebUser;
import com.axin.common.core.constant.CacheConstants;
import com.axin.common.core.constant.SecurityConstants;
import com.axin.common.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * Api用户信息Service业务层处理
 *
 * @Author axin
 * @Date 2021/11/7 14:42
 **/
@Service
public class WebTokenService {

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 创建令牌
     *
     * @param user 用户信息
     * @return 令牌
     */
    public String createToken(WebUser user) {
        String uuid = IdUtil.fastUUID();
        refreshToken(uuid, user);
        return uuid;
    }


    /**
     * 刷新令牌有效期
     *
     * @param uuid token
     * @param user 登录用户
     */
    public void refreshToken(String uuid, WebUser user) {

        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(uuid);
        redisUtils.setEx(userKey, JSON.toJSONString(user), 3, TimeUnit.DAYS);
    }


    /**
     * 构建缓存key
     *
     * @param uuid
     * @return
     */
    private String getTokenKey(String uuid) {
        return CacheConstants.WEB_LOGIN_TOKEN_KEY + uuid;
    }


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public WebUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            WebUser user = redisUtils.get(getTokenKey(token), WebUser.class);
            return user;
        }
        return null;
    }


    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(SecurityConstants.TOKEN_AUTHENTICATION);
        if (StrUtil.isNotEmpty(token) && token.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            token = token.replace(SecurityConstants.TOKEN_PREFIX, "");
        }
        return token;
    }


    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtils.delete(userKey);
        }
    }
}
